package org.example.mail;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author weigang
 * @create 2022-10-27 16:11
 */
@SuppressWarnings("AlibabaThreadShouldSetName")
@Configuration
@Slf4j
public class MailConfig {
    @Bean("emailPool")
//    @Async("emailPool")
    public ExecutorService asyncEmailPool() {
        return TtlExecutors.getTtlExecutorService(
                new ThreadPoolExecutor(0, 1, 1L, TimeUnit.MINUTES,
                        new LinkedBlockingQueue<>(500),
                        new ThreadFactoryBuilder()
                                .setNameFormat("email-pool-%d")
                                .setUncaughtExceptionHandler((thread, ex) -> {
                                    log.info("email pool raised error, ex:{}", Throwables.getStackTraceAsString(ex));
                                })
                                .build(),
                        (r, executor) -> {
                            log.info("email discard, thread pool reject");
                        }));
    }
}
